/*
 * Copyright 2013 meichenhui
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.googlecode.zet.tool.pluginanalyzer;

import java.io.Console;
import java.util.Scanner;

/**
 * 命令行操作界面<br/>
 * 命令:<br/>
 * an : 分析目标插件在指定环境下的依赖情况.格式: an [运行环境路径][,运行环境路径] [要分析的插件路径]
 * 
 * @author meichenhui
 * 
 */
public class ConsoleUI {

    protected static final String PROMPT                   = "ZET > ";

    protected static final String COMMAND_LOG              = "param is [%1$s] : [%2$s]%n";

    protected static final String ERROR_INVALID_COMMAND    = "Invalid command [%1$s] : [%2$s]%n";

    private static final String   ERROR_UNHANDLE_EXCEPTION = "Execution error [%1$s] : [%2$s]%n[%3$s]%n";

    private boolean               turn                     = true;

    public boolean isTurn() {
        return turn;
    }

    public void setTurn(boolean turn) {
        this.turn = turn;
    }

    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            throw new RuntimeException("Invalid runtime!");
        }
        ConsoleUI ui = new ConsoleUI();
        ui.scanningCommandLine(console);
    }

    protected void scanningCommandLine(Console console) {
        do {
            String commandLine = console.readLine(PROMPT);
            Scanner scanner = new Scanner(commandLine);
            if (scanner.hasNext()) {
                String commandName = scanner.next().toUpperCase();
                String args = scanner.hasNext() ? scanner.nextLine().trim() : null;
                try {
                    Commands command = Enum
                            .valueOf(Commands.class, commandName);
                    command.exec(console, args);
                } catch (IllegalArgumentException e) {
                    console.printf(ERROR_INVALID_COMMAND, commandName, args);
                } catch (Exception e) {
                    console.printf(ERROR_UNHANDLE_EXCEPTION, commandName, args, e);
                    System.out.println(e);
                }
            }
        } while (turn);
    }

}
